from cachelib import file
from bs4 import BeautifulSoup
import tkinter as tk
from tkinter import filedialog, messagebox

def browse_file():
    filepath = filedialog.askopenfilename(filetypes=[("HTML files", "*.html")])
    titles = title_entry.get()
    label =label_entry.get()
    if filepath:
        with open(filepath, encoding='utf-8') as file:
            content = file.read()

        html = content
        soup = BeautifulSoup(html, 'html.parser')
        questions = soup.find_all('div', class_='field ui-field-contain')

        for question in questions:
            topic = question['topic']
            title = question.find('div', class_=titles).text.strip()
            options = [option.text.strip() for option in question.find_all('div', class_=label)]
            output_text.insert(tk.END, "{}\n".format(title))
            output_text.insert(tk.END, "选项：\n")
            for option in options:
                output_text.insert(tk.END, "{}\n".format(option))
            output_text.insert(tk.END, "\n")

def on_confirm():
    global title, label
    title = title_entry.get()
    label = label_entry.get()
    if not title or not label:
        messagebox.showerror("错误", "请输入class！")
    else:
        browse_file()
def save_file():
    file_path = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=[("Text files", "*.txt"), ("Word files", "*.docx")])
    if file_path:
        with open(file_path, "w", encoding="utf-8") as file:
            file.write(output_text.get(1.0, tk.END))
        messagebox.showinfo("成功", "文件已保存")

root = tk.Tk()
root.title("网站选择题爬取工具1.0.0(作者微信：yqlh_888)")

frame = tk.Frame(root)
frame.pack(padx=10, pady=10)
title_label = tk.Label(frame, text="标题class：")
title_label.pack(side=tk.LEFT, padx=5)
title_entry = tk.Entry(frame)
title_entry.pack(side=tk.LEFT, padx=5)

label_label = tk.Label(frame, text="选项class：")
label_label.pack(side=tk.LEFT, padx=5)
label_entry = tk.Entry(frame)
label_entry.pack(side=tk.LEFT, padx=5)

confirm_button = tk.Button(frame, text="确认", command=on_confirm)
confirm_button.pack(side=tk.LEFT, padx=5)
save_button = tk.Button(frame, text="保存", command=save_file)
save_button.pack(side=tk.LEFT, padx=5)
output_text = tk.Text(frame, wrap=tk.WORD)
output_text.pack(fill=tk.BOTH, expand=True)

root.mainloop()
